package com.xcity.game.item.drop.impl;

import com.alibaba.fastjson.annotation.JSONField;
import com.xcity.db.entity.Player;
import com.xcity.game.item.ItemTemplate;
import com.xcity.game.item.drop.RangeDrop;
import com.xcity.game.item.drop.listener.DropListener;
import com.xcity.game.item.drop.listener.ItemDropListener;

import naga.x.App;
import naga.x.game.template.TemplateService;
import naga.x.util.CommonUtils;

public class ItemDrop extends RangeDrop {

	protected int id;
	protected ItemTemplate template;
	
	public ItemDrop(int probability, int id, int count) {
		this(probability, 0, id, count, count);
	}
	
	public ItemDrop(int probability, int weight, int id, int min, int max) {
		this.probability = probability;
		this.weight = weight;
		this.id = id;
		this.min = min;
		this.max = max;
	}

	@Override
	protected void processDrop(Player player, String cause, DropListener listener) {
		int count = CommonUtils.randomInt(RND, min, max);
		if (count <= 0) {
			return;
		}
		if (listener != null && listener instanceof ItemDropListener) {
			ItemDropListener lsr = ((ItemDropListener) listener);
			if (player != null) {
				player.getBag().addItemWithoutException(getId(), count, cause, lsr);
			}
			lsr.itemDroped(player, getId(), count);
		} else if (player != null) {
			player.getBag().addItemWithoutException(getId(), count, cause);
		}
	}
	
	public int getId() {
		return id;
	}
	
	public String getName() {
		return getTemplate().getName();
	}
	
	public String getDesc() {
		return getTemplate().getDesc();
	}
	
	public String getIcon() {
		return getTemplate().getIcon();
	}
	
	public int getCount() {
		return max;
	}
	
	public int getMinCount(){
		return min;
	}

	@JSONField(serialize = false)
	public ItemTemplate getTemplate() {
		return template != null ? template : (template = App.getApp().getServiceManager().get(TemplateService.class).get(ItemTemplate.class, id));
	}

}
